<template>
  <a-card v-if="hasHotel" title="酒店信息">
    <a-form
      :model="hotel"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 14 }"
      v-if="hotel"
      :disabled="!editing"
    >
      <a-form-item label="酒店封面">
        <a-upload
          list-type="picture-card"
          :show-upload-list="false"
          :customRequest="uploadLogo"
          :before-upload="beforeUpload"
        >
          <img v-if="hotel.logo" :src="hotel.logo" alt="logo" style="width: 100px;" />
          <div v-else>
            <plus-outlined />
            <div style="margin-top: 8px;">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="酒店照片">
        <a-upload
          list-type="picture-card"
          :file-list="hotel.photos"
          :before-upload="beforePhotoUpload"
          :on-remove="handlePhotoRemove"
          :customRequest="uploadPhoto"
          multiple
        >
          <plus-outlined />
          <div style="margin-top: 8px;">上传</div>
        </a-upload>
      </a-form-item>
      <a-form-item label="酒店名称">
        <a-input v-model:value="hotel.name" />
      </a-form-item>
      <a-form-item label="地址">
        <a-input v-model:value="hotel.address" />
      </a-form-item>
      <a-form-item label="电话">
        <a-input v-model:value="hotel.phone" />
      </a-form-item>
      <a-form-item label="城市">
        <a-input v-model:value="hotel.city" />
      </a-form-item>
      <a-form-item label="简介">
        <a-textarea v-model:value="hotel.desc" rows="3" />
      </a-form-item>
    </a-form>
    <div style="margin-left: 16.6667%;">
      <a-button v-if="!editing" type="primary" @click="editing = true">编辑</a-button>
      <a-button v-else type="primary" @click="save" style="margin-right: 8px;">保存</a-button>
      <a-button v-if="editing" @click="cancel">取消</a-button>
    </div>
  </a-card>
  <a-card v-else title="创建酒店">
    <a-form :model="createForm">
      <a-form-item label="酒店封面">
        <a-upload
          list-type="picture-card"
          :show-upload-list="false"
          :customRequest="uploadCreateFormLogo"
          :before-upload="beforeUpload"
        >
          <img v-if="createForm.logo" :src="createForm.logo" alt="logo" style="width: 100px;" />
          <div v-else>
            <plus-outlined />
            <div style="margin-top: 8px;">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="酒店照片">
        <a-upload
          list-type="picture-card"
          :file-list="createForm.photos"
          :before-upload="beforePhotoUpload"
          :on-remove="(file: any) => { createForm.photos = createForm.photos.filter((f: any) => f.uid !== file.uid); }"
          :customRequest="uploadCreateFormPhoto"
          multiple
        >
          <plus-outlined />
          <div style="margin-top: 8px;">上传</div>
        </a-upload>
      </a-form-item>
      <a-form-item label="酒店名称">
        <a-input v-model:value="createForm.name" />
      </a-form-item>
      <a-form-item label="地址">
        <a-input v-model:value="createForm.address" />
      </a-form-item>
      <a-form-item label="电话">
        <a-input v-model:value="createForm.phone" />
      </a-form-item>
      <a-form-item label="城市">
        <a-input v-model:value="createForm.city" />
      </a-form-item>
      <a-form-item label="简介">
        <a-textarea v-model:value="createForm.desc" rows="3" />
      </a-form-item>
      <div style="margin-left: 16.6667%;">
        <a-button type="primary" @click="handleCreateHotel">创建酒店</a-button>
      </div>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { apiGetHotelInfo, apiCreateHotel, apiUploadHotelImage, apiUpdateHotel } from '@/api/admin-api';
import router from '@/router';
import { useHotelStore } from '@/stores/hotelStrore';

const editing = ref(false);
const hotelStore = useHotelStore();
const hasHotel = computed(() => hotelStore.hasHotel);
const hotel = ref<{ name: string; address: string; phone: string; city: string; desc: string; logo: string; photos: any[] }>(
  {
    name: '我的酒店',
    address: '某市某区某路88号',
    phone: '123-45678901',
    city: '北京',
    desc: '这是一家舒适的酒店，欢迎您的光临。',
    logo: '',
    photos: []
  }
);

const createForm = ref<{ name: string; address: string; phone: string; city: string; desc: string; logo: string; photos: any[] }>(
  {
    name: '',
    address: '',
    phone: '',
    city: '',
    desc: '',
    logo: '',
    photos: []
  }
);

// 上传酒店Logo（编辑模式）
async function uploadLogo({ file, onProgress, onSuccess, onError }: any) {
  const formData = new FormData();
  formData.append('image', file);
  
  try {
    onProgress({ percent: 50 });  // 上传进度
    const res = await apiUploadHotelImage(formData);
    
    if (res && res.data && res.data.code === 200 && res.data.data) {
      hotel.value.logo = res.data.data;
      onProgress({ percent: 100 });
      onSuccess(res.data);
      message.success('Logo上传成功');
    } else {
      onError();
      message.error(res.data?.msg || 'Logo上传失败');
    }
  } catch (error) {
    onError();
    message.error('Logo上传失败');
    console.error('上传Logo出错:', error);
  }
}

// 上传酒店照片（编辑模式）
async function uploadPhoto({ file, onSuccess, onError }: any) {
  const formData = new FormData();
  formData.append('image', file);
  
  try {
    const res = await apiUploadHotelImage(formData);
    
    if (res && res.data && res.data.code === 200 && res.data.data) {
      // 添加新上传的照片到列表中
      const newPhoto = {
        uid: `${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
        name: file.name || 'photo.jpg',
        status: 'done',
        url: res.data.data
      };
      // 更新照片列表
      hotel.value.photos = [...hotel.value.photos, newPhoto];
    
      onSuccess(res.data);
    } else {
      onError();
      message.error(res.data?.msg || '照片上传失败');
    }
  } catch (error) {
    onError();
    message.error('照片上传失败');
    console.error('上传照片出错:', error);
  }
}

// 上传酒店Logo（创建模式）
async function uploadCreateFormLogo({ file, onProgress, onSuccess, onError }: any) {
  const formData = new FormData();
  formData.append('image', file);
  
  try {
    onProgress({ percent: 50 });
    const res = await apiUploadHotelImage(formData);
    
    if (res && res.data && res.data.code === 200 && res.data.data) {
      createForm.value.logo = res.data.data;
      onProgress({ percent: 100 });
      onSuccess(res.data);
      message.success('Logo上传成功');
    } else {
      onError();
      message.error(res.data?.msg || 'Logo上传失败');
    }
  } catch (error) {
    onError();
    message.error('Logo上传失败');
    console.error('上传Logo出错:', error);
  }
}

// 上传酒店照片（创建模式）
async function uploadCreateFormPhoto({ file, onProgress, onSuccess, onError }: any) {
  const formData = new FormData();
  formData.append('image', file);
  
  try {
    onProgress({ percent: 50 });  // 上传进度
    const res = await apiUploadHotelImage(formData);
    
    if (res && res.data && res.data.code === 200 && res.data.data) {
      // 添加新上传的照片到列表中
      const newPhoto = {
        uid: `${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
        name: file.name || 'photo.jpg',
        status: 'done',
        url: res.data.data
      };
      
      createForm.value.photos = [...createForm.value.photos, newPhoto];
      onProgress({ percent: 100 });
      onSuccess(res.data);
    } else {
      onError();
      message.error(res.data?.msg || '照片上传失败');
    }
  } catch (error) {
    onError();
    message.error('照片上传失败');
    console.error('上传照片出错:', error);
  }
}

function beforeUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件');
  }
  return isImage;
}

function beforePhotoUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  if (!isImage) message.error('只能上传图片文件');
  return isImage;
}

function handlePhotoRemove(file: any) {
  hotel.value.photos = hotel.value.photos.filter(f => f.uid !== file.uid);
}

async function save() {
  try {
    // 拼接照片URL字符串
    const submitData = {
      ...hotel.value,
      photos: hotel.value.photos.map((f: any) => f.url).join(',')
    };
    const res: any = await apiUpdateHotel(submitData);
    if (res && res.code === 200) {
      message.success('保存成功');
      editing.value = false;
      await fetchHotelInfo();
      // 更新store中的酒店信息
      hotelStore.getHotelInfo();
    } else {
      message.error(res.msg || '保存失败');
    }
  } catch (e) {
    message.error('保存失败');
  }
}

async function cancel() {
  editing.value = false;
  await fetchHotelInfo(); // 重新拉取后端数据，重置表单
}

async function fetchHotelInfo() {
  try {
    const res: any = await apiGetHotelInfo();
    if (res && res.code === 200) {
      Object.assign(hotel.value, res.data);
      // 处理photos为逗号分隔字符串或数组的情况，补充name和type字段
      if (typeof res.data.photos === 'string') {
        hotel.value.photos = res.data.photos
          ? res.data.photos.split(',').filter(Boolean).map((url: string, idx: number) => ({
              url,
              uid: `${Date.now()}-${idx}`,
              name: url.split('/').pop() || `photo${idx + 1}.jpg`,
              type: 'image/jpeg'
            }))
          : [];
      } else if (Array.isArray(res.data.photos)) {
        hotel.value.photos = res.data.photos.map((file: any, idx: number) => ({
          ...file,
          name: file.name || (file.url ? file.url.split('/').pop() : `photo${idx + 1}.jpg`),
          type: file.type || 'image/jpeg',
          uid: file.uid || `${Date.now()}-${idx}`
        }));
      } else {
        hotel.value.photos = [];
      }
      hotelStore.setHasHotel(true);
    } else if (res && res.code === 500) {
      hotelStore.setHasHotel(false);
    }
  } catch (e) {
    console.log(e);
    hotelStore.setHasHotel(false);
  }
}

onMounted(async () => {
  await fetchHotelInfo();
  // 同步store中的状态
  if (!hotelStore.isInitialized) {
    await hotelStore.getHotelInfo();
  }
});

async function handleCreateHotel() {
  try {
    // 拼接照片URL字符串
    const submitData = {
      ...createForm.value,
      photos: createForm.value.photos.map((f: any) => f.url).join(',')
    };
    const res: any = await apiCreateHotel(submitData);
    if (res && res.code === 200) {
      message.success('创建酒店成功');
      hotelStore.setHasHotel(true);
      // 重新获取酒店信息，更新store
      await hotelStore.getHotelInfo();
      await fetchHotelInfo();
    } else {
      message.error(res.msg || '创建酒店失败');
    }
  } catch (e) {
    message.error('创建酒店失败');
  }
}

</script> 